package com.example.hans.databaseandroid;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

import tools.LoginPacket;
import tools.LoginReplayPacket;
import tools.LogonPacket;
import tools.Service;
import tools.Util;


/**
 * 登陆活动
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText mETName;
    private EditText mETPassword;
    private Button mBtuLogIn;
    private String mName;
    private String mPassword;
    private List<User> users;
    private boolean isPress = false;
    boolean mRun = true;
    LoginReplayPacket lrPacket = new LoginReplayPacket();
    private static String TAG = "LoginActivity";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    if (lrPacket.getFlag() == 1) {
                        //账号密码匹配正确

                        //登陆的用户保存到软件信息参数  下次不用再登陆
                        SharedPreferences sp = getSharedPreferences("loginInfo",MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();//获取编辑器
                        editor.putString("username", lrPacket.getName());
                        editor.putBoolean("isLogin", true);
                        editor.apply();//提交修改


                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);

                    } else if(lrPacket.getFlag() == -1) {
                        //密码错误
                        showLogInFail("密码错误");

                    } else {
                        //无该用户
                        showLogInFail("用户名错误");
                    }
                }
                default: {
                    super.handleMessage(msg);
                }
            }
        }
    };

    public void initView() {
        mETName = findViewById(R.id.et_name);
        mETPassword = findViewById(R.id.et_password);
        mBtuLogIn = findViewById(R.id.btn_log_in);


        new Thread(mSocketRunnable).start();
        mBtuLogIn.setOnClickListener(this);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.log_in_layout);
        initView();
    }



    private Socket mSocket;
    private Runnable mSocketRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d("ChatActivity", "Thread start run");
            mRun = true;
            try {
                Log.d("ChatActivity", "start connect to 10.0.2.2");
                mSocket = new Socket("192.168.5.2", 2018);
                Log.d("ChatActivity", "after connect to 10.0.2.2");
                OutputStream out = mSocket.getOutputStream();
                InputStream in = mSocket.getInputStream();
                byte[] readBuffer = new byte[1024];
                while(mRun) {
                    if (isPress) {
                        LoginPacket packet = new LoginPacket();
                        packet.userName = mName;
                        packet.password = mPassword;
                        out.write(packet.serialize());
                        out.flush();
                        int length = in.read(readBuffer);
                        int packetType = Util.bytes2int(readBuffer, 4);
                        if (packetType == Service.PACKET_TYPE.S2C_LOGIN) { //登陆的返回包
                            lrPacket.unserialize(readBuffer);
                            Log.d(TAG,lrPacket.getName());
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = lrPacket;
                            mHandler.sendMessage(msg);
                        }
                        isPress = false;
                    }
                    Thread.sleep(1000);
                }

                mSocket.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    public void getData() {
        //获取输入的用户名和密码
        mName = mETName.getText().toString();
        mPassword = mETPassword.getText().toString();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_log_in: {
                getData();

                isPress = true;
                boolean f = true;
//                users = DataSupport.where("name = ?",mName).find(User.class);
//                if (users.size() < 1) {
//                    showLogInFail("没有该用户");
//                    break;
//                }
//                for (User u:users) {
//                    if (u.getPassword().equals(mPassword)) {
//                        Intent intent = new Intent(this,MainActivity.class);
//                        startActivity(intent);
//                        f = false;
//                    }
//                }
//                if (f) {
//                    showLogInFail("密码错误");
//                }
                break;
            }
            default:
        }
    }

    public void showLogInFail(String msg) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("登录失败");
        dialog.setMessage(msg);
        dialog.setCancelable(false);
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.setNegativeButton("再试一次", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();
    }
}
